import { ref } from "vue";
import type { Ref } from "vue";
import { defineStore } from "pinia";
import { fetchFilterListAPI, fetchGoodsListAPI } from "@/api/subCategoryApi/subCategoryApi.ts";
import type { Page, SalePropertie } from "@/types/subCategoryTypes/interface.ts";
import type { Brand, Good } from "@/types/homeTypes/homeTypes.ts";
import type { PageParams } from "@/types/subCategoryTypes/subCategoryTypes.ts";
import type { subCategoryStoreInterface } from "@/pinia/modules/subCategoryStore/interface.ts";

const useSubCategoryStore = defineStore("subCategoryStore", (): subCategoryStoreInterface => {
   /*商品品牌属性列表*/
   const brandAttribute: Ref<Brand[]> = ref<Brand[]>([]);
   /*商品属性列表*/
   const salePropAttribute: Ref<SalePropertie[]> = ref<SalePropertie[]>([]);
   /*商品列表*/
   const goodsList: Ref<Good[]> = ref<Good[]>([]);
   /*商品列表总数*/
   const counts: Ref<number> = ref<number>(0);
   /*是否选中品牌*/
   const selectBrand: Ref<null | string> = ref<null | string>(null);
   /*获取筛选列表的请求函数*/
   const fetchFilterList = async (id: string): Promise<void> => {
      const { result: { brands, saleProperties } } = await fetchFilterListAPI(id);
      brands.unshift({ id: null, name: "全部" } as Brand);
      brandAttribute.value = brands;
      saleProperties.forEach(saleProp => {
         saleProp.properties.unshift({ id: null, name: "全部" });
         saleProp.selectProp = null;
      });
      salePropAttribute.value = saleProperties;
   };
   /*获取商品列表的请求函数*/
   const fetchGoodsList = async (pageParams: PageParams): Promise<void> => {
      const { result }: { result: Page } = await fetchGoodsListAPI(pageParams);
      counts.value = result.counts;
      goodsList.value = result.items;
   };
   return {
      brandAttribute,
      salePropAttribute,
      goodsList,
      counts,
      selectBrand,
      fetchFilterList,
      fetchGoodsList,
   };
});

export default useSubCategoryStore;
